import "dart:io";

import "package:ct_pa_majordomo/pages/transfer_station.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:dio/dio.dart";
import "package:flutter/foundation.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

final Dio request = Dio(
  BaseOptions(
    // baseUrl: "http://36.140.137.233:180/prod-api/",
    baseUrl: "https://www.ctqct.net/prod-api/",
    // baseUrl: "http://www-lqc.ctqct.net/prod-api/",
    // baseUrl: "http://192.168.0.101:8080/",
    // baseUrl: "http://172.18.192.1:8080/",
    contentType: ContentType.json.toString(),
    sendTimeout: const Duration(seconds: 15),
    receiveTimeout: const Duration(seconds: 15),
  ),
)..interceptors.add(BaseInterceptor());

class BaseInterceptor extends Interceptor {
  // 添加静态标志位，防止401错误重复处理
  static bool _isHandling401 = false;
  
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    String token = storage.getString("token") ?? "";
    if (token.isNotEmpty) options.headers["Authorization"] = "Bearer $token";
    if (kDebugMode) {
      print("REQUEST >>>>>>>>>>>>>>>>>>>>");
      print("${options.method}: ${options.uri}");
      print("data: ${options.data}");
      print("<<<<<<<<<<<<<<<<<<<< REQUEST");
    }
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    RequestOptions options = response.requestOptions;
    if (kDebugMode) {
      print("RESPONSE >>>>>>>>>>>>>>>>>>>>");
      print("${options.method}: ${options.uri}");
      print("data: ${response.data}");
      print("<<<<<<<<<<<<<<<<<<<< RESPONSE");
      print("");
    }
    if (response.data is Map && response.data["code"] != 200) {
      if (response.data["code"] == 401) {
        // 检查是否已经在处理401错误，避免重复处理
        if (!_isHandling401) {
          _isHandling401 = true;
          storage.remove("token");
          storage.remove("apartment");
          storage.remove("info");
          // Stacker.pushAndRemoveUntil(const TransferStation());
          Stacker.pushReplacementNamed(Keys.LOGIN);
          
          // 2秒后重置标志位，防止长期锁定
          Future.delayed(const Duration(seconds: 2), () {
            _isHandling401 = false;
          });
        }
      } else if (response.data["code"] == 500) {
        EasyLoading.showToast(response?.data["msg"] ?? "服务异常，请联系管理员");
      }
      return handler.reject(
        DioException(response: response, requestOptions: options),
        true,
      );
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (kDebugMode) {
      print("Error >>>>>>>>>>>>>>>>>>>>");
      print("${err.requestOptions.method}: ${err.requestOptions.uri}");
      print("statusCode: ${err.response?.statusCode}");
      print("error: $err");
      print("<<<<<<<<<<<<<<<<<<<< Error");
    }
    EasyLoading.showToast(err.response?.data["msg"] ?? "网络请求失败");
    super.onError(err, handler);
  }
}
